﻿
using ZDK.Infra.Services;
using System.Windows.Threading;
using System.Windows.Controls;

namespace ZDK.Utilities
{
    public class MyLog : IMyLog
    {
        static readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(MyLog));

        public void Error(string msg)
        {
            _log.Error(msg);
        }

        public void Info(string msg)
        {
            _log.Info(msg);
        }

        public void Warn(string msg)
        {
            _log.Warn(msg);
        }
    }

    public class TextBoxAppender : log4net.Appender.AppenderSkeleton
    {
        public TextBox TextBox { get; set; }
        readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;

        public TextBoxAppender() { }

        protected override void Append(log4net.Core.LoggingEvent loggingEvent)
        {
            if (TextBox == null)
                return;

            var patternLayout = Layout as log4net.Layout.PatternLayout;
            var str = string.Empty;
            if (patternLayout != null)
            {
                str = patternLayout.Format(loggingEvent);

                if (loggingEvent.ExceptionObject != null)
                {
                    str += loggingEvent.ExceptionObject.ToString() + System.Environment.NewLine;
                }
            }
            else
            {
                str = loggingEvent.LoggerName + "-" + loggingEvent.RenderedMessage + System.Environment.NewLine;
            }

            _dispatcher.Invoke(new System.Action(() =>
            {
                if (TextBox.LineCount == 1000)
                {
                    TextBox.Text = "";
                }
                TextBox.AppendText(str);
                TextBox.ScrollToEnd();
            }));
        }

        public void ClearLog()
        {
            TextBox.Clear();
        }
    }
}
